from __future__ import print_function, absolute_import
from gm.api import *
import pandas as pd
import os.path

import numpy as np
def init(context):
    # 设置标的
    context.symbol = 'SHFE.cu2110'
    # 订阅一分钟线
    subscribe(symbols=context.symbol, frequency='60s', count=10)
    # 记录开仓次数，保证一天只开仓一次
    context.count = 0
    # 记录当前时间
    time = context.now.strftime('%H:%M:%S')
    # 如果当前时间点是交易时间段，则直接执行algo获取历史数据，以防直接进入on_bar()导致context.history_data未定义
    if '09:00:00' < time < '15:00:00' or '21:00:00' < time < '23:00:00':
        algo(context)

    # 如果是非交易时间段，等到上午9点或晚上21点再执行algo()
    schedule(schedule_func=algo, date_rule='1d', time_rule='09:00:00')
    schedule(schedule_func=algo, date_rule='1d', time_rule='21:00:00')


def algo(context):
    # 获取历史的n条信息
    file_dir = './his_data/'+context.symbol
    if not os.path.exists(file_dir):  # 判断是否存在文件夹如果不存在则创建为文件夹
        os.makedirs(file_dir)
    else:
        filename = file_dir + '/'+ str(context.now).split(' ')[0] + '.csv'
        if not os.path.exists(filename):  # 判断是否存在文件如果不存在则创建
            info = get_instrumentinfos(symbols=[context.symbol], df=True)
            date = str(context.now).split(' ')[0]
            yes_date = get_previous_trading_date(info.exchange[0], date)
            s_time = yes_date + ' 20:55:00'
            context.his = history(context.symbol, '60s', s_time, context.now,
                                  # fields='symbol,open,high,low,close, eob',
                                  skip_suspended=True,
                                  fill_missing=None, adjust=ADJUST_NONE, adjust_end_time='', df=True)
            context.his = context.his.set_index('eob')
            context.his.index = [str(x)[:19] for x in context.his.index]
            context.his.index = pd.to_datetime(context.his.index, format="%Y-%m-%d %H:%M:%S")
            context.his.to_csv(filename)
        else:
            csv_df = pd.read_csv(filename)
            csv_df = csv_df.set_index(csv_df.columns[0])
            csv_df.index.name = 'eob'
            s_time = csv_df.index[-1]

            new_his = history(context.symbol, '60s', s_time, context.now,
                                  # fields='symbol,open,high,low,close, eob',
                                  skip_suspended=True,
                                  fill_missing=None, adjust=ADJUST_NONE, adjust_end_time='', df=True)
            new_his = new_his.set_index('eob')
            new_his.index = [str(x)[:19] for x in new_his.index]
            new_his.index = pd.to_datetime(new_his.index, format="%Y-%m-%d %H:%M:%S")
            context.his = pd.concat([csv_df, new_his], axis=0).drop_duplicates()
            context.his.to_csv(filename)
    context.filename = filename
    print(context.his)

def on_bar(context, bars):
    # 取出订阅的一分钟bar
    bar = bars[0]
    data = context.data(symbol=context.symbol, frequency='60s', count=9).set_index('eob')
    data.index = [str(x)[:19] for x in data.index]
    data.index = pd.to_datetime(data.index, format="%Y-%m-%d %H:%M:%S")
    daily_all = pd.concat([context.his, data], axis=0).drop_duplicates()
    daily_all.to_csv(context.filename)
    print(daily_all)


if __name__ == '__main__':
    '''
    strategy_id策略ID,由系统生成
    filename文件名,请与本文件名保持一致
    mode实时模式:MODE_LIVE回测模式:MODE_BACKTEST
    token绑定计算机的ID,可在系统设置-密钥管理中生成
    backtest_start_time回测开始时间
    backtest_end_time回测结束时间
    backtest_adjust股票复权方式不复权:ADJUST_NONE前复权:ADJUST_PREV后复权:ADJUST_POST
    backtest_initial_cash回测初始资金
    backtest_commission_ratio回测佣金比例
    backtest_slippage_ratio回测滑点比例
    '''
    run(strategy_id='ed7ee067-12e2-11ec-9e9a-88d7f6dad8a6',
        filename='juejin_hq.py',
        mode=MODE_LIVE,
        token='5be220861ce35a6f97f9398d7967fde449f8ddaf',
        backtest_adjust=ADJUST_PREV,
        backtest_initial_cash=100000,
        backtest_start_time='2020-04-01 09:00:00',
        backtest_end_time='2020-05-31 15:00:00',
        backtest_commission_ratio=0.0001,
        backtest_slippage_ratio=0.0001)